package com.learning.bean;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class URLDownload implements Runnable {
	String spec;
	final String dstpath = "E:/";

	public URLDownload(String spec) {
		super();
		this.spec = spec;
	}

	@Override
	public void run() {
		try {
			URL url = new URL(spec);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			BufferedInputStream is = null;
			BufferedOutputStream os = null;
			String suf = suffix(spec);
			if (conn.getResponseCode() == 200) {
				is = new BufferedInputStream(conn.getInputStream());
				os = new BufferedOutputStream(new FileOutputStream(dstpath
						+ suf));
				int b = 0;
				while ((b = is.read()) != -1) {
					os.write(b);
					os.flush();
				}
				System.out.println("congratuations");
				is.close();
				os.close();
				Thread.sleep(2000);
				System.out.println("-----------------");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String suffix(String url2) {
		int index = url2.lastIndexOf(".");
		return (int) (Math.random() * 10000) + url2.substring(index);
	}
}
